package df.applet.form;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.sql.ResultSet;
import java.sql.SQLException;

import java.util.List;

import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTable;

//my import
import javax.swing.table.DefaultTableModel;

import df.bean.db.conn.DBConnection;
import df.bean.obj.doctor.*;
import df.bean.obj.util.DialogBox;
import df.bean.obj.util.Variables;
import df.bean.process.Process;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.ListSelectionModel;

public class CalculatorFrm extends JFrame {
    public JPanel jPanelLayout = new JPanel();
    public JList lstDoctorGroupCode = new JList();
    public JTable tblMessage = null; //new JTable();
    public JLabel statusBar = new JLabel();
    
    public JScrollPane scrollPane;// = new JScrollPane();
    public JScrollPane scrollPaneMessage;// = new JScrollPane();
    
    public JList lstHospitalCode = new JList();
    public JScrollPane scrollPaneHospitalCode;
    public JLabel lblHospital = new JLabel();
    public JLabel lblDoctor = new JLabel();

    public int row = 0;
    public ImageIcon imageStart = new ImageIcon(CalculatorFrm.class.getResource("start.gif"));
    public ImageIcon imageStop = new ImageIcon(CalculatorFrm.class.getResource("stop.gif"));
    public ImageIcon imageClose = new ImageIcon(CalculatorFrm.class.getResource("close.gif"));
    
    public JButton start = new JButton();
    public JButton stop = new JButton();
    public JButton close = new JButton();
    public JSeparator jSeparator4 = new JSeparator();
    public JLabel jLabel1 = new JLabel();
    public JSeparator jSeparator5 = new JSeparator();
    
    public DBConnection conn = new DBConnection();
        
    public String hospitalCode = "";
    public String userId = "";
    public Process process = null;
    public DefaultTableModel tableModel;
    
    public JPanel jPanel1 = new JPanel();
    public JPanel jPanel2 = new JPanel();
    public JPanel jPanel3 = new JPanel();
    public JTextArea jTextArea1 = new JTextArea();
    public JSeparator jSeparator1 = new JSeparator();
    
    public CalculatorFrm() {
        try {
            this.jbInit();
        } catch (Exception e) {
            DialogBox.ShowError("Error in CalculatorFrm\n"+e.getMessage());
            e.printStackTrace();
        }
    }
    
    public void setVariables(String userId, String password, String hospitalCode) {
        Variables.setUserID(userId);
        Variables.setPassword(password);
        Variables.setHospitalCode(hospitalCode);
    }
    
    @Override
    public void finalize() {
        tblMessage = null;
        if (conn.IsOpened()) {          
            conn.Close();
        }
        conn = null;
    }
    
    public boolean connect() {
        boolean ret = false;
        try {
            /// connect to database
            conn = new DBConnection();
            if (conn.connectToLocal()) {
                ret = true;
            } else {
                DialogBox.ShowError("CalculatorFrm.connect() : Connect to database fail. !!!!");
            }
            
        } catch (Exception e) {
        	System.out.println("Summary Monthly : "+e);
            e.printStackTrace();
            DialogBox.ShowError("CalculatorFrm.connect() : Error in calculateFRM");
        }

        return ret;
    }
    
    private void jbInit() throws Exception {
        this.setSize(new Dimension(821, 645));
        jPanelLayout.setLayout(null);
        //jPanelLayout.setBackground(new Color(214, 214, 255));
        jPanelLayout.setBackground(new Color(221, 228, 232));
        jPanelLayout.setOpaque(false);
        getLstDoctorGroupCode().setBounds(new Rectangle(5, 80, 200, 330));
        statusBar.setText( "Status :" );

        start.setIcon(imageStart);
        start.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        start_actionPerformed(e);
                    }
                });
        stop.setIcon(imageStop);
        stop.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        stop_actionPerformed(e);
                    }
                });
        close.setIcon(imageClose);
        close.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        close_actionPerformed(e);
                    }
                });
        
        getLstDoctorGroupCode().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);        
        scrollPane = new JScrollPane(getLstDoctorGroupCode());
        scrollPane.setBounds(new Rectangle(20, 265, 120, 305));
        jPanelLayout.add(getLblDoctor(), null);
        jPanelLayout.add(getLblHospital(), null);
        
        // scroll pane for hospital
        scrollPaneHospitalCode = new JScrollPane(getLstHospitalCode());
        scrollPaneHospitalCode.setBounds(new Rectangle(20, 205, 120, 50));
       
        //Table Scroll Pane
         String[] columnNames={ "Time", "Invoice No", "Invoice Date", "Line No", "Doctor Code", "Order Item", "Remark" }; 
//                         , "Hospital", "Inv No","Inv Date","Bill No","Rev Date","Department", "Location", "HN#", "PTName", "Order Item Code", "Billing Sub Group No",
//                         "Rec Mode", "Rec Type", "Payment Module", "Doctor", "Inv Amt", "Inv_Discount_Amt", 
//                         "Rec Amt", "Rec Premium Amt", "Nor Allocate_Amt", "Nor Allocate Pct", 
//                         "Dr Amt", "Dr Amt 402", "Dr Amt 406", "Dr Premium", "Dr TaxBase", "Tax Type", 
//                         "HP_Amt", "HP Premium", "HP_Tax", "Status_Code", "Admission Type", 
//                         "Dr Treatment Code", "Premium Pct", "Premium Vat", "Order Date", "Category", "Ex_Treatment", "Premium Rec Amt"};
        tableModel = new DefaultTableModel(columnNames, row);
        tblMessage = new JTable(tableModel);
        scrollPaneMessage = new JScrollPane(tblMessage); 
        scrollPaneMessage.setBounds(new Rectangle(150, 205, 645, 365));
        jPanelLayout.add(jSeparator5, null);
        jPanelLayout.add(close, null);
        jPanelLayout.add(stop, null);
        jPanelLayout.add(start, null);
        jPanelLayout.add(scrollPaneMessage, BorderLayout.CENTER);
        jPanelLayout.add(scrollPaneHospitalCode, null);
        jPanelLayout.add(scrollPane, null);
        jPanelLayout.add(jPanel1, null);
        jPanelLayout.add(jPanel3, null);
        jPanelLayout.add(jTextArea1, null);
        jPanelLayout.add(jSeparator4, null);
        jPanelLayout.add(jSeparator1, null);
        tblMessage.setAutoscrolls(true);
        tblMessage.setAutoResizeMode(0);


        //        start.setText("Start");
        start.setBounds(new Rectangle(560, 115, 55, 30));
        start.setActionCommand("Start");
        start.setToolTipText("Start");
        //        stop.setText("Stop");
        stop.setBounds(new Rectangle(625, 115, 55, 30));
        stop.setActionCommand("Stop");
        stop.setToolTipText("Stop");
        //        close.setText("Close");
        close.setBounds(new Rectangle(695, 115, 55, 30));
        close.setActionCommand("Close");
        close.setToolTipText("Close");
        jSeparator4.setBounds(new Rectangle(25, 110, 765, 90));

        jPanel1.setBounds(new Rectangle(25, 65, 765, 45));
        jPanel1.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
        jPanel1.setBackground(new Color(214, 214, 214));
        jPanel1.setForeground(Color.white);
        jPanel2.setBounds(new Rectangle(25, 25, 765, 40));
        jPanel2.setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
        jPanel2.setBackground(new Color(99, 99, 99));
        jPanel2.setForeground(Color.white);
        jPanel3.setBounds(new Rectangle(25, 110, 765, 40));
        jPanel3.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
        jPanel3.setBackground(new Color(99, 99, 99));
        jPanel3.setForeground(Color.white);
        jTextArea1.setBounds(new Rectangle(20, 20, 775, 135));
        jTextArea1.setBackground(new Color(231, 231, 231));
        jSeparator1.setBounds(new Rectangle(25, 65, 765, 115));
        jSeparator5.setBounds(new Rectangle(20, 180, 775, 30));
        getLstHospitalCode().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        jPanelLayout.add(scrollPane, null);
        getContentPane().add(jPanelLayout, BorderLayout.CENTER);

        this.setHospitalCode("null");
    }
    
    public void addDoctorGroupToList(String hospitalCode) {
        this.getLstDoctorGroupCode().removeAll();
        DefaultListModel model = elementAdd(hospitalCode);
        this.getLstDoctorGroupCode().setModel(model);
    }
    
    public DefaultListModel elementAdd(String hospitalCode) {
        DefaultListModel r = new DefaultListModel();
        String sql = "select CODE from DOCTOR where HOSPITAL_CODE = '" + hospitalCode + "'";
        sql = sql + " order by CODE";
        
        ResultSet rs = conn.executeQuery(sql);
        try {
            r.clear();
            while (rs.next()) {
                r.addElement(rs.getString("code"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
               //Clean up resources, close the connection.
               if(rs != null) {
                  try {
                     rs.close();
                     rs = null;
                    }
                  catch (Exception ignored) { ignored.printStackTrace();   }
            }
        }
        return r;
    }
    
    public void setTableValue(List lst) {
//        if (this.tableModel.getRowCount() >= 200) { this.tableModel.removeRow(0);  }
        Object[] object = new String[lst.size()];
        for (int i=0; i<lst.size(); i++) {
            if (lst.get(i) != null)
                object[i] = lst.get(i).toString();
            else 
                object[i] = " ";
        }
        tableModel.addRow(object);
    }
    public void setErrorMessage(List lst) {
//        if (this.tableModel.getRowCount() >= 200) this.tableModel.removeRow(0);
        Object[] object = new String[lst.size()];
        for (int i=0; i<lst.size(); i++) {
            if (lst.get(i) != null)
                object[i] = lst.get(i).toString();
            else 
                object[i] = " ";
        }
        
        tableModel.addRow(object);  
        tblMessage.setBackground(Color.RED);
//        tblMessage.setSelectionBackground(Color.RED);
    }

    protected void close_actionPerformed(ActionEvent e) {
        this.setVisible(false);
    }

    protected void start_actionPerformed(ActionEvent e) {
        if (this.conn.IsOpened()) { this.connect();  addHospitalCodeToList();  }
    }
    
    public CareProvider newCareProvider(String className) {
        CareProvider cpv = null;
        try {
            Class careProviderClass = Class.forName( className, true, ClassLoader.getSystemClassLoader() );
            cpv = (CareProvider)careProviderClass.newInstance();
        } catch( Exception err ) {
            err.printStackTrace();
        }
        return cpv;
    }
    

    protected void stop_actionPerformed(ActionEvent e) {
        this.stopProcess();
    }


    public String getHospitalCode() {
        return hospitalCode;
    }

    public void setHospitalCode(String hospitalCode) {
        this.hospitalCode = hospitalCode;
    }

    public JList getLstDoctorGroupCode() {
        return lstDoctorGroupCode;
    }

    public void setLstDoctorGroupCode(JList lstDoctorGroupCode) {
        this.lstDoctorGroupCode = lstDoctorGroupCode;
    }

    public JList getLstHospitalCode() {
        return lstHospitalCode;
    }

    public void setLstHospitalCode(JList lstHospitalCode) {
        this.lstHospitalCode = lstHospitalCode;
    }

    public Process getProcess() {
        return process;
    }

    public void setProcess(Process process) {
        this.process = process;
    }
    
    // hospital list
    public void addHospitalCodeToList() {
        DefaultListModel model = elementAddToHospitalCodeList();
        this.getLstHospitalCode().setModel(model);
    }
    
    public DefaultListModel elementAddToHospitalCodeList() {
        DefaultListModel r = new DefaultListModel();
        String sql;
        sql = "select CODE from HOSPITAL where CODE like '" + Variables.getHospitalCode() + "' order by CODE"; 
        
        ResultSet rs = conn.executeQuery(sql);
        try {
            while (rs.next()) {
                r.addElement(rs.getString("code"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
               //Clean up resources, close the connection.
               if(rs != null) {
                  try {
                     rs.close();
                     rs = null;
                    }
                  catch (Exception ignored) { ignored.printStackTrace();   }
            }
        }
        return r;
    }

    public JLabel getLblHospital() {
        return lblHospital;
    }

    public void setLblHospital(JLabel lblHospital) {
        this.lblHospital = lblHospital;
    }

    public JLabel getLblDoctor() {
        return lblDoctor;
    }

    public void setLblDoctor(JLabel lblDoctor) {
        this.lblDoctor = lblDoctor;
    }
    public void startProcess() {
        
    }
    public void stopProcess() {
        if (this.getProcess() != null) {
            this.getProcess().running = false;
            this.getProcess().working = false;
            this.setStop();     
        }
    }
    
    public void setRun() {
        this.start.setEnabled(false);
        this.stop.setEnabled(true);
    }
    public void setStop() {
        this.start.setEnabled(true);
        this.stop.setEnabled(false);        
    }
    public void setCount(String mess) {
        this.jLabel1.setText(mess);
    }
//    private void this_componentResized(ComponentEvent e) {
//        scrollPaneMessage.setSize(jPanelLayout.getWidth()-110, jPanelLayout.getHeight()-60);
//        this.scrollPane.setSize(this.scrollPane.getWidth(), jPanelLayout.getHeight()-185);
//       // jToolBarDFCalculator.setSize(jPanelLayout.getWidth(), jToolBarDFCalculator.getHeight());
//    }    
}
